<template>
  <div>
    <!-- 添加广告组 -->
    <div class="example">
        <a-spin size="large" tip="Loading..." :spinning="spinning" />
    </div>
    <div v-if="spinning ==false">

    <a-tabs :defaultActiveKey="tabs" @change="callback">
      <a-tab-pane key="1" tab="创建新广告组">
           <a-form :form="form">
            <a-form-item
                :label="$t('推广目的')"
                :labelCol="{span: 2}"
                :wrapperCol="{span: 200}"
                :required="true"
            >
                <div class="layui-row objectivebox" ref="typetip" prop="typetip">
                    <div class="layui-col-md2" @click="actives($event,'1')" :class="[typeshow==1 ? 'actives' : '']">
                        <input type="hidden" name="landing_type" value="APP">
                        <div class="campaign-card-tip">
                            <strong>应用推广</strong>
                            <p>提升应用的下载、安装、激活、付费</p>
                        </div>
                        <div class="campaign-card-img">
                            <img :src="imgurl('campaign-app.svg')" alt="">
                        </div>
                        <div v-show="typeshow==1">
                        <div class="checkobjective">
                            <a-icon type="check" />
                        </div>
                        </div>
                    </div>
                    <div class="layui-col-md2" @click="actives($event,'2')" :class="[typeshow==2 ? 'actives' : '']">
                        <input type="hidden" name="landing_type" value="LINK">
                        <div class="campaign-card-tip">
                            <strong>销售线索收集</strong>
                            <p>提升销售线索的获取量</p>
                        </div>
                        <div class="campaign-card-img">
                            <img :src="imgurl('campaign-external.svg')" alt="">
                        </div>
                        <div v-show="typeshow==2">
                        <div class="checkobjective">
                            <a-icon type="check" />
                        </div>
                        </div>
                    </div>

                    <div class="layui-col-md2" @click="actives($event,'3')" :class="[typeshow==3 ? 'actives' : '']">
                        <input type="hidden" name="landing_type" value="AWEME">
                        <div class="campaign-card-tip">
                            <strong>抖音号推广</strong>
                            <p>提升抖音号的粉丝量、互动量</p>
                        </div>
                        <div class="campaign-card-img">
                            <img :src="imgurl('campaign-aweme.svg')" alt="">
                        </div>
                         <div v-show="typeshow==3">
                        <div class="checkobjective">
                            <a-icon type="check" />
                        </div>
                         </div>
                    </div>
                </div>
            </a-form-item>
             <a-form-item
                :label="$t('广告组预算：')"
                :labelCol="{span: 2}"
                :wrapperCol="{span: 10}"
                :required="true"
                >
                <div class="form-row">
                    <a-button @click="onbudget($event,'1')" :type="[primary==1 ? 'primary' : '']">不限</a-button>
                    <a-button @click="onbudget($event,'2')" :type="[primary==2 ? 'primary' : '']">预算</a-button>
                </div>
             </a-form-item>
             <div class="disnon" :style="{display:isblock}">
                <a-form-item
                    :label="$t('日预算')"
                    :labelCol="{span: 2}"
                    :wrapperCol="{span: 10}"
                    :required="true"
                    >
                    <div class="form-row">
                    <a-input-number id="inputNumber"
                    v-decorator="[
                        'budget',
                    ]"
                     style="width:200px;" v-model="value" :min="0" :max="9999999.99" :step="0.0" />
                    </div>
                </a-form-item>
             </div>
             <a-form-item
                :label="$t('广告组名称')"
                :labelCol="{span: 2}"
                :wrapperCol="{span: 10}"
                 :required="true"
                >
                <div class="form-row">
                  <a-input v-decorator="[
				'name',
                { rules: [{ required: true, message: '请输入广告名称' }] }
				]" placeholder="请输入广告组名称" />
                </div>
             </a-form-item>

             <a-form-item
                :label="$t('广告组账户')"
                :labelCol="{span: 2}"
                :wrapperCol="{span: 10}"
                 :required="true"
                >
                <div class="form-row">
                   <a-select
                    show-search
                    placeholder="请选择广告主账户"
                    option-filter-prop="children"
                    style="width: 200px"
                    v-decorator="[
                        'advertiser_id',
                        {rules:[],initialValue:''}
                    ]"
                >
                    <a-select-option  v-for="item in options" :key="item.account_id" :value="item.account_id">
                        {{ item.name }}
                    </a-select-option>
                </a-select>
                </div>
             </a-form-item>

              <a-form-item
                :label="$t('广告组状态')"
                :labelCol="{span: 2}"
                :wrapperCol="{span: 10}"
                >
                <div class="form-row">
                    <a-switch default-checked @change="onChange" />
                </div>

              </a-form-item>
              <div style="margin-left:135px;">
               <a-popconfirm
                    title="您确定要取消新增广告组吗?"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="cancels"
                >
                <a-button  size="large" style="margin-right:10px;">
                    取消
                </a-button>
                </a-popconfirm>
                <a-button type="primary" @click="determines" :loading="logging" size="large">
                    确定
                </a-button>
              </div>
               
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" tab="选择已有广告组" force-render v-if="tabs ==2">

        <a-form layout="horizontal" :form="form2" @submit="handleSubmit">
             <a-form-item
              label="关键词搜索"
              :labelCol="{span: 2}"
              :wrapperCol="{span: 6}"
            >
                <a-input-search placeholder="请输入广告组ID或名称" v-decorator="['key']" enter-button @search="onSearch" />
            </a-form-item>
             <a-form-item
              label="广告账户"
              :labelCol="{span: 2}"
              :wrapperCol="{span: 6}"
              :required="true"
            >
                <a-select
                    show-search
                    placeholder="请选择广告账户"
                    option-filter-prop="children"
                    style="width: 200px"
                    v-decorator="['adveracount']"
                    :filter-option="filterOption"
                    @change="handleChange"
                >
                    <a-select-option v-for="(item,index) in options" :key="index" :value="item.account_id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </a-form-item>
        </a-form>
        

        <!-- 已有广告组 -->
         <a-table
            :columns="columnsdata"
            :dataSource="datalist.list"
            @clear="onClear"
            :pagination="paginationOpt"
            :width="650"
            :loading='tableloading'
            style="width:650px;"
            :scroll="{ x: 650 }"
        >
        <div slot="nameDemo" slot-scope="item">
            <a slot="title" @click="tolink(item.id,item.landing_type,item.account_id)">
                {{ item.name }}
                <span style="float:right;" v-if="item.landing_type =='LINK'">信息流-销售线索收集</span>
                <span style="float:right;" v-if="item.landing_type =='APP'">信息流-应用推广</span>
                <span style="float:right;" v-if="item.landing_type =='DPA'">信息流-商品目录推广</span>
                <span style="float:right;" v-if="item.landing_type =='GOODS'">信息流-商品推广（鲁班）</span>
                <span style="float:right;" v-if="item.landing_type =='STORE'">信息流-门店推广</span>
                <span style="float:right;" v-if="item.landing_type =='AWEME'">信息流-抖音号推广</span>
                <span style="float:right;" v-if="item.landing_type =='SHOP'">信息流-电商店铺推广</span>
                <span style="float:right;" v-if="item.landing_type =='ARTICAL'">信息流-头条文章推广</span>
            </a>
        </div>
        </a-table>
    
      </a-tab-pane>
    </a-tabs>
    </div>
  </div>
</template>
<script>
import {ACCOUNTURL,ADVER,ADDADURL} from '@/services/api'
import {ajax,ajaxnoparams,ajaxparems} from '@/services/ajaxrequest'
var options =[];
var data = new Object();
const datalist = [];
var columnsdata = [{
    title:'',
    scopedSlots: { customRender: 'nameDemo' }
}];
export default {
    created(){
        this.tabs = this.$route.query.tabs;
        this.listNew();
        this.listNewpage();
	},
	beforeCreate() {
    this.form = this.$form.createForm(this);
    this.form2 = this.$form.createForm(this);
    },
  data() {
    return {
        spinning:true,
        typeshow:0,
        options:options,
        primary:1,
        isblock:'none',
        switchons:true,
       
        datalist,
        tabs:'',
        logging:false,
        columnsdata,
        account_id:'',
        tableloading:false,
        paginationOpt: {
			defaultCurrent: 1, // 默认当前页数
			defaultPageSize: 10, // 默认当前页显示数据的大小
			total: 0, // 总数，必须先有
			showSizeChanger: true,
			showQuickJumper: true,
			pageSizeOptions: ["5", "10", "15", "20"],
			showTotal: (total) => `共 ${total} 条`, // 显示总数
			onShowSizeChange: (current, pageSize) => {
				this.paginationOpt.defaultCurrent = 1;
				this.paginationOpt.defaultPageSize = pageSize;
				this.listNew(); //显示列表的接口名称
			},
			// 改变每页数量时更新显示
			onChange: (current, size) => {
				this.paginationOpt.defaultCurrent = current;
				this.paginationOpt.defaultPageSize = size;
				this.listNew();
			},
		},
    };
  },
  methods: {
    handleChange(e){
        this.account_id= e;
        //请求已有广告组
        this.tableloading = true;
        const { defaultCurrent, defaultPageSize } = this.paginationOpt;
        this.form2.validateFieldsAndScroll((err, values) => {
            var adparemss = [];
            if(values['key'] !=undefined && values['key'] !=''){
				adparemss.push({"field":"name","operator":"LIKE","value":values['key']})
			}
            if(e !=undefined && e !=''){
				adparemss.push({"field":"account_id","operator":"EQUALS","value":e})
                adparemss.push({"field":"status","operator":"NOT_IN","value":["CAMPAIGN_STATUS_DELETE"]});
			}
            if(adparemss.length >0){
                var parems = {
                    page:defaultCurrent,
                    page_size:defaultPageSize,
                    "filtering":adparemss,
                };
                ajaxparems(ADVER,parems).then((res) => {
                    var result=res.data;
                    if(result.code =="SUCCESS"){
                        this.tableloading = false;
                        this.paginationOpt.total = result.data.page_info.total;
                        this.datalist =result.data;
                    }else{
                        this.tableloading = false;
                        this.$message.error(result.message);
                    }
                })
            }else{
                this.paginationOpt.total = 0;
                this.tableloading = false;
            }
        })
    },
    tolink(e,type,account_id){
        this.$router.push({
            path: '/promotion/advering/addplan/',
            query: {
                campaign_id: e,
                landing_type:type,
                account_id:account_id
            }
        })
    },
    onSearch() {
        // var adveracount = this.form.getFieldValue("adveracount");
        // var parems = {"filtering":[
        //     {"field":"account_id","operator":"EQUALS","value":adveracount},
        //     {"field":"name","operator":"LIKE","value":value},
        // ]};
        // ajaxparems(ADVER,parems).then((res) => {
        //     var result=res.data;
        //     if(result.code =="SUCCESS"){
        //         this.datalist =result.data;
        //     }else{
        //         this.$message.error(result.message,3);
        //     }
        // })
        this.listNew();
    //     var numReg = /^[0-9]*$/
    //     var numRe = new RegExp(numReg)
    //     var values = "";
    //     if (!numRe.test(value)) {
          
    //        values = {"campaign_name":value};
    //     }else{
    //          values = {"ids":[value]};
    //     }
    //     var parems = {"filtering":values};

    //    ajaxrequest("1657869217074189", ADVER,parems).then((res) => {
    //         var result=res.data;
	// 		this.datalist =result.data.list;
	// 	})
    },
    actives:function (e,num) {
       this.typeshow = num;
    },
    onbudget:function (e,num){
        if(num ==2){
            this.primary =2;
            this.isblock = "block";
        }else{
            this.primary =1;
            this.isblock = "none";
        }
    },

    listNew(){
        this.tableloading = true;
        const { defaultCurrent, defaultPageSize } = this.paginationOpt;
        this.form2.validateFieldsAndScroll((err, values) => {
            var adparems = [];
            if(values['key'] !=undefined && values['key'] !=''){
				adparems.push({"field":"name","operator":"LIKE","value":values['key']})
			}

            if(values['adveracount'] !=undefined && values['adveracount'] !=''){
				adparems.push({"field":"account_id","operator":"EQUALS","value":values['adveracount']})
                adparems.push({"field":"status","operator":"NOT_IN","value":["CAMPAIGN_STATUS_DELETE"]});
			}

            console.log(values);

            // console.log(adparems);
            if(adparems.length >0){
                var parems = {
                    page:defaultCurrent,
                    page_size:defaultPageSize,
                    "filtering":adparems,
                };
                ajaxparems(ADVER,parems).then((res) => {
                    var result=res.data;
                    if(result.code =="SUCCESS"){
                        this.tableloading = false;
                        this.paginationOpt.total = result.data.page_info.total;
                        this.datalist =result.data;
                    }else{
                        this.tableloading = false;
                        this.$message.error(result.message);
                    }
                })
            }else{
                this.paginationOpt.total = 0;
                this.tableloading = false;
            }
        })
    },

    listNewpage(){
        //请求广告主账户列表
        ajax(ACCOUNTURL,"").then((res) => {
            var result=res.data;
            // console.log(result);
            if(result.code =="SUCCESS"){
                this.options =result.data;
            }else{
                this.$message.Error(result.message, 3)
            }
        });
        this.spinning = false;
    },
    cancels(){
        this.$router.push('/promotion/advering/advers')
    },
    determines(){
        this.logging = true;
        this.form.validateFieldsAndScroll((err, values) => {
            var types = this.typeshow;
            if(types =="0"){
                 this.$message.error("请选择推广目的", 3);
                 return;
            }else if(types =="1"){
                data.landing_type = "APP";
            }else if(types =="2"){
                data.landing_type = "LINK";
            }else if(types =="3"){
                data.landing_type = "AWEME";
            }
            
            var primary = this.primary;
            if(primary ==2){
                if(values.budget ==undefined){
                    this.$message.error("请输入预算值", 3);
                    return;
                }
                data.budget = values.budget;
                data.budget_mode = "BUDGET_MODE_DAY";
            }else{
                data.budget_mode = "BUDGET_MODE_INFINITE";
            }
            data.campaign_name = values.name;
            data.advertiser_id = this.form.getFieldValue('advertiser_id');
            var switchon = this.switchons;
            if(switchon ==true){
                data.operation = "disable";
            }else{
                data.operation ="enable";
            }
            var parems = data;

			ajaxnoparams(data.advertiser_id,ADDADURL,parems).then((res) => {
				var result=res.data;
				if(result.code =="SUCCESS"){
                    this.logging = false;
                    if(this.tabs ==2){
                         this.$message.success(result.message, 3).then(
                            this.$router.push({
                                path: '/promotion/advering/addplan/',
                                query: {
                                    campaign_id: result.data.campaign_id,
                                    landing_type:data.landing_type
                                }
                            })
                        );
                    }else{
                        this.$message.success(result.message, 3).then(
                            this.$router.push('/promotion/advering/advers/?ii=1')
                        );
                        this.reload();
                    }
				}else{
                    this.logging = false;
 					this.$message.error(result.message, 3)
				}
			})
		});
    },
    onChange(checked) {
        // console.log(checked);
        this.switchons = checked;
    },
    imgurl (name){
      return require('@/assets/img/'+name);
    }
  },
};
</script>

<style scoped>
  .example {
    text-align: center;
    background: rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    margin-bottom: 20px;
    /* padding: 30px 50px; */
    margin: 20px 0;
  }
.ant-layout{
    background: #fff;
}
/* 广告组推广目的 */
.objectivebox .layui-col-md2{
    width:275px;
    height: 125px;
    position: relative;
    display: inline-block;
}
.disnon{
    display: none;
}

.objectivebox .layui-col-md2 .campaign-card-tip{
    width: 106px;
    display: inline-block;    
    font-size: 14px;
    color: #333;
    text-align: left;
    /* padding:20px; */
    padding:20px 0 20px 20px;
    float:left;
}

.campaign-card-tip strong{
    font-weight: 700;
}

.campaign-card-tip p{
    margin-top: 10px;
    font-size: 12px;
    color:#999;
    font-weight: 300;
    line-height:1.1;
}

.objectivebox .layui-col-md2{
    border: 1px solid #EDF1F5;
    box-shadow: 0px 2px 10px 0px rgb(0 0 0 / 5%);
    border-radius: 4px;
    margin-right: 16px;
    margin-top: 10px;
    cursor: pointer;
    position: relative;
}

.objectivebox .layui-col-md2 .campaign-card-img{
    width: 120px;
    height: 120px;
    display: inline-block;
}

.objectivebox .layui-col-md2 .campaign-card-img img{
    display: block;
    /* padding-top: 20px; */
}
.objectivebox .actives{
    border-bottom:3px solid #338aff;
    height:125px;
}

.objectivebox .checkobjective{
    position: absolute;
    right: 10px;
    top: 10px;
    /* display: none; */
}

.objectivebox .checkobjective i{
    font-size: 20px;
    font-weight: bold;
    color:#338aff;
}
</style>
